package com.example.demo.Aspect;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.example.demo.Entity.Log;
import com.example.demo.Repository.ILogRepository;

@Component
@Aspect
@Order(2)
public class LoggerAspect {

	
	@Autowired
	private ILogRepository logRepository;
	
	@Pointcut("@annotation(com.example.demo.Aspect.Logging)")
	public void logging() {
	}
	
	@Before("logging()")
	public void logRecord(JoinPoint joinpoint) throws Throwable{
		Object[] args=joinpoint.getArgs();
		String keyword=((HttpServletRequest)args[0]).getParameter("Keyword");
		Log log=logRepository.findByName(keyword);
		if(log==null) {
			log=new Log();
			log.setName(keyword);
			log.setWeight(1);
			logRepository.save(log); 
			List<Log> list=logRepository.findAll();
			if(list.size()>40) {
				Integer i=logRepository.findAllinOrder().get(21).getWeight();
				for(Log l:list) {
					if(l.getWeight()<=i)
					logRepository.delete(l);
				}
			}
		}
		else {
			log.setWeight(log.getWeight()+1);
			logRepository.save(log);
		}
	}
}
